import cherrypy, sqlite3, os, random, math
from CoreFunctions import LogEvents, LogEvent
from CoreFunctions import GetConfig, GetSetting
class MovieTest:
    global SQL
    
    def __init__(self):
        self.DBName         = ""
        
    def index(self):
        pass
        index.exposed = True
	
    def search(self, searchtext=None, page=1, initial=None, genresearch=None, newmovies='False'):
        #self.Layout = 2
        
        if GetConfig('settings.ini'):
            self.MovieFolder        = GetSetting("Common", "MovieFolder")    #"/Movies" #"c:\\temp\\temp"
            self.DBName             = GetSetting("Common", "DBName")         #"/Movies/Python/MovieDB.db"
            self.LogFile            = GetSetting("Common", "LogFile")
            self.PAGESIZE           = int(GetSetting("MovieTest", "PageSize"))
            self.Layout             = int(GetSetting("MovieTest", "Layout"))
            self.StaticDir          = GetSetting("MovieTest", "StaticDir")
            self.HTTPAlias          = GetSetting("MovieTest", "HTTPAlias")
            self.BackgroundsFolder  = GetSetting("MovieTest", "BackgroundsFolder")
            self.ShowSearch         = int(GetSetting("MovieTest", "ShowSearch"))
            self.ShowClock          = int(GetSetting("MovieTest", "ShowClock"))
            self.DefaultCover       = GetSetting("MovieTest", "DefaultCover")
            self.ImagesFolder       = GetSetting("MovieTest", "ImagesFolder")
            self.OSSeperator        = GetSetting("Common", "OSSeperator")
            self.NextButton         = GetSetting("MovieTest", "NextButton")
            self.BackButton         = GetSetting("MovieTest", "BackButton")
            self.BackgroundOption   = int(GetSetting("MovieTest", "BackgroundOption"))
            self.DefaultBackground  = GetSetting("MovieTest", "DefaultBackground")
            self.AppFolder			= GetSetting("MovieTest", "AppFolder")
        self.cn = sqlite3.connect(self.DBName)
        
        LogEvents('a', self)
        #LogEvent("Search")
        #LogEvent("Loading Settings")
        #LogEvent("Movie folder is " + self.MovieFolder)
        #LogEvent("DB is " + self.DBName)
        #LogEvent("PAGESIZE is " + str(self.PAGESIZE))
        #LogEvent("Layout is " + str(self.Layout))
        #LogEvent("BackgroundsFolder is " + self.BackgroundsFolder)
        #LogEvent("ShowSearch is " + str(self.ShowSearch))
        #LogEvent("ShowClock is " + str(self.ShowClock))
        #LogEvent("DefaultCover is " + str(self.DefaultCover))        		
        #LogEvent("ImagesFolder is " + self.ImagesFolder)
        #LogEvent("OSSeperator is " + self.OSSeperator)
        #LogEvent("NextButton is " + str(self.NextButton))
        #LogEvent("BackButton is " + str(self.BackButton))
        #LogEvent("BackgroundOption is " + str(self.BackgroundOption))
        #LogEvent("DefaultBackground is " + str(self.DefaultBackground))
        #LogEvent("AppFolder is " + str(self.AppFolder))
	
        self.DefaultImage = self.ImagesFolder + self.OSSeperator + self.DefaultCover
        self.Next = self.ImagesFolder + self.OSSeperator + self.NextButton
        self.Back = self.ImagesFolder + self.OSSeperator + self.BackButton
        background = ""
        trHTML=""
        anchorlist = ""
        HTML = ""
        
        infile = open('Pages/MainScreen.html', 'r')
        lines = infile.readlines()
        infile.close()
        HTML=""
        for line in lines:
            HTML+=line
        
        searchform      = ""
        clock           = ""
        if self.ShowClock:
            clock = "<strong><span id='clock' class='large'>&nbsp;</span></strong>"
        
        #create a list of backgrounds then choose one randomly
        if self.BackgroundOption==1:
            backgrounds = []
            for bgs in os.walk(self.BackgroundsFolder):
                backgrounds.append(bgs[2])
            backint     = random.randrange(0, len(backgrounds[0])-1,1)    
            background  = self.BackgroundsFolder + "\\"  + str(backgrounds[0][backint])
            #LogEvent("Background is " + background)
			
        pgfHTML = "&nbsp;"
        pgbHTML = "&nbsp;"
        rows    = None
        
        #set some defaults for the initial load of the page
        SQL = "SELECT count(*) from tblMovies ORDER BY Title LIMIT 10 "
        
		
        searchHTML = ""
        if searchtext!=None:
            searchHTML = "searchtext"
            SQL = "select  count(IMDBID) from vwActorMovies where title like '" + searchtext + "' or actorfirstname like '" + searchtext + "' or actorlastname like '" + searchtext + "' "
            if searchtext!='%':
                SQL = "select  count(IMDBID) from vwActorMovies where title like '%" + searchtext + "%' or actorfirstname like '%" + searchtext + "%' or actorlastname like '%" + searchtext + "%' or actorid like '%" + searchtext + "%'"
                LogEvent("SQL is " + SQL)					
        elif initial!=None:
            searchHTML = "initial"
            searchtext = initial
            SQL = "SELECT count(IMDBID) FROM tblMovies WHERE Title like '" + initial + "%' "
            #LogEvent("SQL is " + SQL)        
        elif genresearch!=None:
            searchtext = genresearch
            searchHTML = "genresearch"
            SQL = "SELECT count(IMDBID) FROM tblMovies WHERE Genre like '%" + genresearch + "%' "
            #LogEvent("SQL is " + SQL)			
        elif newmovies.lower()=='true':
            searchtext = newmovies
            searchHTML = "newmovies"
            SQL = "SELECT count(IMDBID) FROM tblMovies where date(julianday(dateadded)) >= date(julianday(date('now') )-7)"
            #LogEvent("SQL is " + SQL)			
            #yield(SQL)
        else:
            initial = "A"
            searchHTML = "initial"
            searchtext = initial
            SQL = "SELECT count(IMDBID) FROM tblMovies WHERE Title like '" + initial + "%' "

        #LogEvent("Searchtext is " + searchtext)				
        #LogEvent("SearchHTML is " + searchHTML)				
        #LogEvent("SQL is " + SQL)				
        try:    
            #LogEvent("Performing initial query: " + SQL)
            self.cn = sqlite3.connect(self.DBName)
            self.cursor = self.cn.execute(SQL)
            moviecount = self.cursor.fetchall()
            #LogEvent("Query found " + str(moviecount))
        except Exception, x:
            LogEvent(str(x))
        
        #get the genre list
        try:
            #LogEvent("Building genre list")
            SQL = "SELECT Genre FROM tblGenres ORDER BY Genre"
            genrelist = "<a class='genres' href=search?newmovies=true>New</a><br>"
            self.cursor = self.cn.execute(SQL)
            genres = self.cursor.fetchall()
            if genres:
                for genre in genres:
                    genrelist += "<a class='genres' href=search?genresearch=" + str(genre[0]) + ">" + str(genre[0]) + " </a>" + "<br>"
            #LogEvent("Genre list is " + genrelist)
        except Exception, x:
            LogEvent(str(x))
                
        #get the list of first characters from the movies titles -e.g. A C F R T W
        try:
            #LogEvent("Building list of first chars")
            SQL = "select distinct substr(title,1,1) from tblMovies order by title"
            Initials = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
            self.cursor = self.cn.execute(SQL)
            titlechars = self.cursor.fetchall()
            if titlechars:
                Initials = []
                for titchar in titlechars:
                    if titchar[0]!="":
                        Initials.append(str(titchar[0]))
            #LogEvent("Title chars are " + str(Initials))
        except Exception, x:
            LogEvent(str(x))
            
        #figure out our paging
        page = int(page)
        #LogEvent("Page is " + str(page))
		
        if moviecount:
            rowcount = moviecount[0][0]
            pages = (rowcount / self.PAGESIZE) + 1
            #LogEvent("Number of pages is " + str(pages))
            #yield("Pages " + str(rowcount))
            if pages > 1:
                if page < pages:
                    pgfHTML = "<a href='search?" + searchHTML + "=%s&page=%s'><img src='%s' width='15' height='50' alt='Next page...'></a>" %(searchtext, str(page+1), self.Next)
                if page > 1:
                    pgbHTML = "<a href='search?" + searchHTML + "=%s&page=%s'><img src='%s' width='15' height='50' alt='Previous page...'></a>" %(searchtext, str(page-1), self.Back)    
            #LogEvent("pgfHTML is " + pgfHTML)   
            #LogEvent("pgbHTML is " + pgbHTML)			
            SQL = "SELECT MoviePath, Title, Plot, MovieCover FROM tblMovies WHERE Title like 'A%' ORDER BY Title LIMIT 10"
            if searchtext!=None:
                SQL = "select distinct MoviePath, Title, Plot, MovieCover, IMDBID, MovieFanart from tblMovies inner join tblMovieActors on tblMovies.IMDBID = tblMovieActors.MovieID inner join tblActors on tblMovieActors.ActorID = tblActors.ActorID where title like '%" + searchtext + "%' or actorfirstname like '%" + searchtext + "%' or actorlastname like '%" + searchtext + "%' or tblActors.actorid like '%" + searchtext + "%' ORDER BY Title  LIMIT 10  OFFSET  " +str( (page-1) * 10)
                #SQL = "SELECT MoviePath, Title, Plot, MovieCover, IMDBID, MovieFanart  FROM tblMovies WHERE Title like '%" + searchtext + "%' ORDER BY Title  LIMIT 8  OFFSET  " +str( (page-1) * 8)
            if initial!=None:
                SQL = "SELECT MoviePath, Title, Plot, MovieCover, IMDBID, MovieFanart  FROM tblMovies WHERE Title like '" + initial + "%' ORDER BY Title  LIMIT 10  OFFSET  " +str( (page-1) * 10)
            if genresearch!=None:
                SQL = "SELECT MoviePath, Title, Plot, MovieCover, IMDBID, MovieFanart  FROM tblMovies WHERE Genre like '%" + genresearch + "%' ORDER BY Title  LIMIT 10  OFFSET  " +str( (page-1) * 10)  
                #yield(SQL)   
            if newmovies.lower()=='true':
                SQL = "SELECT MoviePath, Title, Plot, MovieCover, IMDBID, MovieFanart FROM tblMovies where date(julianday(dateadded)) >= date(julianday(date('now') )-7) LIMIT 10  OFFSET  " +str( (page-1) * 10)
            SQL = SQL.replace("%%%", "%")
            LogEvent(SQL)
            #LogEvent("Performing actual search...")            
            #self.cursor = None
            try:
                #LogEvent("Searching...")  
                #self.cn.close()    
                #self.cn = sqlite3.connect(self.DBName)          
                self.newcursor = self.cn.execute(SQL)
                newrows = self.newcursor.fetchall()
                #LogEvent("Search found "  + str(newrows))
                
            except Exception, x:
                LogEvent(str(x))
                #LogEvent("Search found " )
         
        #create the search form and initials
        if self.ShowSearch:
            searchform = "<span id='searchform'><form action='search' name='search'><input type=submit value='go'><input type=text size=5 name='searchtext'></form></span>"
        InitialHTML="<a href='search?initial=" + '%' + "'>All</a>&nbsp;"
        for initial in Initials:
            InitialHTML+="<a href='search?initial=%s'>%s</a>&nbsp;" % (initial, initial)
        
        #LogEvent("InitialHTML is " + InitialHTML)		
		
        #create the main table of titles 
        #LogEvent("Checking for results in recordset " + str(rows))		
        try:
            if newrows:
                #LogEvent("We have some results")			
                #get the background here if option 2
                if self.BackgroundOption==2:
                    if len(newrows)>0:
                        backint     = random.randrange(0, len(newrows),1)   
                        background   = str(newrows[backint][5]).replace("c:","") 
                
                trrows = (len(newrows)+1)/5
                #yield(str(trrows))
                vod=""
                try:
                    if self.Layout==1: 
                        #LogEvent("Layout is 1") 
                        for row in newrows:
                            if ".jsp" in row[0]:
                                vod = "playlist"  
                            HTML = "<tr align=center>"
                            HTML += '<td width="225" align="center"><img src="%s" width="150" height="225"></td><td><a href="file:///opt/sybhttpd/localhost.drives/NETWORK_SHARE%s" TVID="play" name="1" vod="%s">%s</a></td><td class="normal">%s</td>' % (row.MovieCover.replace("c:",""), row.MoviePath.replace(" ", "%20").replace("\\", "/"), vod, row.Title, row.Plot)
                            HTML += "</tr>"
                            #yield(HTML)
                            
                    if self.Layout==2:
                        #LogEvent("Layout is 2")                         
                        trrow       = 0
                        tdcount     = 1
                        trimginc    = 0
                        tdlist=["<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>","<td width=180>&nbsp;</td>"]
                        #LogEvent("Creating TD list")       
                        #LogEvent("No of items in recordset:" + str(newrows[0]))
                        for row in newrows:
                                #LogEvent("Found playlist in " + str(row[0])	)
								
                            if row[3]!="None":    
                                imgsrc = str(row[3]).replace(" ", "%20").replace("'", "\'")
                            else:
                                imgsrc = self.DefaultImage
                            #LogEvent("Added " + imgsrc)                            
                            #tdcontent = '<td width="250" align="center"><a href="file:///opt/sybhttpd/localhost.drives/NETWORK_SHARE%s" TVID="play" name="1" vod="%s"><img border=2 src="%s" width="200" height="290"></a></td>' % (row[0], vod, imgsrc)
                            tdcontent = '<td width="180" align="center"><a name="%i" onfocus="show(%i)" onblur="hide(%i)" href="MovieDetails?IMDBID=%s"><img border=0 src="%s" width="175" height="262" onmouseover="show(%i)" onmouseout="hide(%i)"></a></td>' % (tdcount, tdcount,tdcount, row[4], imgsrc.replace("C:",""), tdcount, tdcount)
                            
                            tdlist[tdcount]=tdcontent 
                            #LogEvent("Added " + tdcontent)                                
                            anchorlist+="<a class='title' id='title%s'>%s</a>" % (str(tdcount), row[1])
                            #add the anchor to the anchorlist
                            tdcount+=1
 
                        while trrow < 2:
                            trHTML+="<tr valign=top height=270>%s%s%s%s%s</tr>" % (tdlist[1+trimginc], tdlist[2+trimginc],tdlist[3+trimginc],tdlist[4+trimginc],tdlist[5+trimginc])
                            trimginc    = 5
                            trrow       +=1
                        
                        
                    #yield(HTML)
                           
                except Exception, x:
                    LogEvent(str(x))
            
            if background in ["None", "", 'none']:
                background = self.ImagesFolder + self.OSSeperator + self.DefaultBackground
                
            HTML = HTML.replace("{pgfHTML}",pgfHTML)
            HTML = HTML.replace("{page}", str(page))
            HTML = HTML.replace("{pages}", str(pages)) 
            HTML = HTML.replace("{genrelist}",genrelist)
            HTML = HTML.replace("{searchform}",searchform)
            HTML = HTML.replace("{InitialHTML}",InitialHTML)
            HTML = HTML.replace("{background}",background)
            HTML = HTML.replace("{pgbHTML}",pgbHTML)
            HTML = HTML.replace("{trHTML}", trHTML)
            HTML = HTML.replace("{clock}", clock)
            HTML = HTML.replace("{css}", self.AppFolder + self.OSSeperator)
            HTML = HTML.replace("{anchorlist}", anchorlist)
            HTML = HTML.replace("{pictures}", self.ImagesFolder)
            HTML = HTML.replace("c:","").replace("C:","")
            yield HTML 
            
            if self.cn:
                self.cn.close()
        except Exception, x:
                LogEvent(str(x))
                
        #yield("")
    
        
    search.exposed = True
    
    def MovieDetails(self, IMDBID=None):
        if IMDBID!=None:
            
            if GetConfig('settings.ini'):
                self.MovieFolder        = GetSetting("Common", "MovieFolder")    #"/Movies" #"c:\\temp\\temp"
                self.DBName             = GetSetting("Common", "DBName")         #"/Movies/Python/MovieDB.db"
                self.LogFile            = GetSetting("Common", "LogFile")
                #self.PAGESIZE           = int(GetSetting("MovieTest", "PageSize"))
                #self.Layout             = int(GetSetting("MovieTest", "Layout"))
                #self.StaticDir          = GetSetting("MovieTest", "StaticDir")
                #self.HTTPAlias          = GetSetting("MovieTest", "HTTPAlias")
                #self.BackgroundsFolder  = GetSetting("MovieTest", "BackgroundsFolder")
                #self.ShowSearch         = int(GetSetting("MovieTest", "ShowSearch"))
                #self.ShowClock          = int(GetSetting("MovieTest", "ShowClock"))
                #self.DefaultCover       = GetSetting("MovieTest", "DefaultCover")
                self.ImagesFolder       = GetSetting("MovieTest", "ImagesFolder")
                self.OSSeperator        = GetSetting("Common", "OSSeperator")
                #self.NextButton         = GetSetting("MovieTest", "NextButton")
                #self.BackButton         = GetSetting("MovieTest", "BackButton")
                #self.BackgroundOption   = int(GetSetting("MovieTest", "BackgroundOption"))
                #self.DefaultBackground  = GetSetting("MovieTest", "DefaultBackground")
                self.AppFolder            = GetSetting("MovieTest", "AppFolder")
                self.PathToNMTShare      = GetSetting("MovieTest", "PathToNMTShare")
            self.cn = sqlite3.connect(self.DBName)
            
            SQL = "SELECT MoviePath, Title, substr(Plot,1,500), MovieCover, Genre, VideoAspect, Director, Studio, VideoCODEC, VideoWidth, " \
                  "VideoHeight, AudioCODEC, AudioChannels, Rating, Country, Year, MovieFanart " \
                  "FROM tblMovies WHERE IMDBID='%s'" % IMDBID
            self.cursor = self.cn.execute(SQL)
            rows = self.cursor.fetchall()
            if rows:
                for row in rows:
                    infile = open('Pages/Details.html', 'r')
                    lines = infile.readlines()
                    infile.close()
                    output=""
                    for line in lines:
                        output+=line
                    output = output.replace("{title}", row[1])
                    output = output.replace("{plot}", row[2])
                    output = output.replace("{cover}", row[3])
                    output = output.replace("{genre}", row[4])
                    output = output.replace("{aspect}", row[5])
                    output = output.replace("{director}", row[6])
                    output = output.replace("{studio}", row[7])
                    output = output.replace("{video}", row[8] + " " + row[9] + "x" + row[10])
                    output = output.replace("{audio}", self.MakeAudioDetails(row[11], row[12]))
                    output = output.replace("{audiocodec}", row[11])
                    output = output.replace("{rating}", row[13])
                    output = output.replace("{country}", row[14])
                    output = output.replace("{year}", row[15])
                    output = output.replace("{background}", row[16])
                    output = output.replace("{css}", self.AppFolder + self.OSSeperator)
                    output = output.replace("{pictures}", self.ImagesFolder)
                    
                    ratingint = '1'
                    try:
                        ratingint = row[13].replace(".", "")[0]
                    except Exception, x:
                        pass
                    output = output.replace("{ratingint}", ratingint)
                    output = output.replace("{actors}", self.GetActors(IMDBID))
                    
                    vod=""
                    if ".jsp" in row[0]:
                        vod = "playlist"
                    moviepath = self.PathToNMTShare + row[0]
                    output = output.replace("{moviepath}", moviepath)
                    output = output.replace("{vod}", vod)    
                    break
            output = output.replace("c:","").replace("C:","")    
            yield(output)
        
    MovieDetails.exposed = True
    def MakeAudioDetails(self, AudioCODEC, AudioChannels):
        AudioDetails = "MP3"
        if AudioChannels=='2':
            AudioDetails = "MP3"
        if AudioChannels=='6':
            if AudioCODEC=="AC3":
                AudioDetails = "ac3"
            if AudioCODEC=="":
                AudioDetails = "dts"    
  
        return AudioDetails
    def GetActors(self, IMDBID):
        ActorList = ""
        SQL = "select ActorID, ActorFirstName, ActorLastName, ActorRole from vwMovieActors where IMDBID = '%s'" % IMDBID
        try:
            self.cursor = self.cn.execute(SQL)
            rows = self.cursor.fetchall()
            if rows:
                for row in rows:
                    try:
                        ActorName = row[1] + " " + row[2] + " (" + row[3] + ")"
                        ActorList+="""
                        <a href='actordetails?actorid=%s'>%s</a><br>                
                        """ % (row[0], ActorName)
                    except Exception, x:
                        LogEvent(str(x))
        except Exception, x:
            LogEvent(str(x))
        return ActorList
    
    def MakeInitialList(self):
        yield("Initials")
         
        yield(InitialHTML)
    
    def ActorDetails(self, ActorID=None):
        if ActorID!=None:
            if GetConfig('settings.ini'):
                self.MovieFolder        = GetSetting("Common", "MovieFolder")    #"/Movies" #"c:\\temp\\temp"
                self.DBName             = GetSetting("Common", "DBName")         #"/Movies/Python/MovieDB.db"
                self.LogFile            = GetSetting("Common", "LogFile")
                #self.PAGESIZE           = int(GetSetting("MovieTest", "PageSize"))
                #self.Layout             = int(GetSetting("MovieTest", "Layout"))
                #self.StaticDir          = GetSetting("MovieTest", "StaticDir")
                #self.HTTPAlias          = GetSetting("MovieTest", "HTTPAlias")
                #self.BackgroundsFolder  = GetSetting("MovieTest", "BackgroundsFolder")
                #self.ShowSearch         = int(GetSetting("MovieTest", "ShowSearch"))
                #self.ShowClock          = int(GetSetting("MovieTest", "ShowClock"))
                #self.DefaultCover       = GetSetting("MovieTest", "DefaultCover")
                self.ImagesFolder       = GetSetting("MovieTest", "ImagesFolder")
                self.OSSeperator        = GetSetting("Common", "OSSeperator")
                #self.NextButton         = GetSetting("MovieTest", "NextButton")
                #self.BackButton         = GetSetting("MovieTest", "BackButton")
                #self.BackgroundOption   = int(GetSetting("MovieTest", "BackgroundOption"))
                #self.DefaultBackground  = GetSetting("MovieTest", "DefaultBackground")
                #self.AppFolder            = GetSetting("MovieTest", "AppFolder")
                #self.PathToNMTShare      = GetSetting("MovieTest", "PathToNMTShare")
            self.cn = sqlite3.connect(self.DBName)
            SQL = "SELECT ActorFirstName, ActorLastName, ActorThumb FROM tblActors WHERE ActorID = '%s'" % ActorID
            self.cursor = self.cn.execute(SQL)
            actorrows = self.cursor.fetchall()
            if actorrows:
                
                infile = open('Pages/ActorDetails.html', 'r')
                lines = infile.readlines()
                infile.close()
                HTML=""
                for line in lines:
                    HTML+=line
                
                for actorrow in actorrows:
                    ActorName = actorrow[0] + " " + actorrow[1]
                    HTML = HTML.replace("{actorname}", ActorName)
                    break
            yield(HTML)
                 
    ActorDetails.exposed = True
#MDB = MovieTest()    
#MDB.index()
settings = {
           'global': {
            'server.socket_port' : 8080,
            'server.socket_host': "0.0.0.0",
            'server.socket_file': "",
            'server.socket_queue_size': 5,
            'server.protocol_version': "HTTP/1.0",
            'server.log_to_screen': True,
            'server.log_file': "",
            'server.reverse_dns': False,
            'server.thread_pool': 10,
            'server.environment': "development",
            'static_filter.root': "/",
            'logDebugInfoFilter.logBuildTime': False,
            'logDebugInfoFilter.logPageSize': False 
            }, 
            '/':{
            'static_filter.on': True,
            'static_filter.dir': "/Movies"     
            }
            }

cherrypy.root = MovieTest()
cherrypy.config.update(settings)
cherrypy.server.start()    
        